
package com.compuvest.feed

import javax.servlet.ServletConfig

import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class GoogleService extends HttpServlet {

    def mysql, mail, googlefeed, bookmakerfeed, datafeed

    def void init(ServletConfig config) {
	super.init(config)

        mysql = new MySQL()
        mail  = new GoogleEmail()

        googlefeed      = new GoogleFeed()
        bookmakerfeed   = new BookmakerFeed()
        datafeed        = new DataFeed()
    }

    def void processRequest(request, response) {

        response.setContentType("text/html;charset=UTF-8")

        def exec = request.getParameter("exec")
        if(!exec) { return }

        def out = response.getWriter()
        try {
            def token = googlefeed.getToken()
            //println '>>>token=' << token

            if(exec == 'readallstock') {

                if(token != 'Error') {

                    //println ">>>do allproducts token=${token}"

                    // clean active status
                    mysql.resetGoogleActive()

                    out.write("<html><head><title>Read all stock from google</title></head><body style='font-size:10px;'>")
                    out.print("<small>token=${token}</small>")

                    // write to file
                    //new File("/tmp/readallstock.txt").withWriter { outfile ->
                    //    outfile.writeLine("sku")

                    def product, nextLink, entries
                    //for( count in 0..5 ) {
                    for(def count = 0; true; count += googlefeed.max_result) {

                        product = googlefeed.getExparedAllStock(nextLink)
                        //println "product=" << product

                        if(product != 'Error') {
                            entries = datafeed.parseFeed(product)

                            mysql.setGoogleActive(entries)

                            nextLink = datafeed.getNextLink()
                        }

                        // write to file
                        //entries.each { accwareid, entity ->
                        //    outfile.writeLine("${accwareid}")
                        //}

                        //println "count:${count} memory(total:free):${Runtime.getRuntime().totalMemory()} : ${Runtime.getRuntime().freeMemory()} nextLink=${nextLink}"
                        out.write("<li>${count} memory:tl:${Runtime.getRuntime().totalMemory()} f:${Runtime.getRuntime().freeMemory()} nextLink=${nextLink}</li>")
                        out.flush()

                        if(nextLink == null)  break // no more
                    }
                    out.write("</body></html>")
                    //} // new File
                } // token != 'Error'
            } // exec = allproduct
            else if(exec == 'search') { // GoogleFeed

                def res = googlefeed.getPublicSearch(request.getParameter("query"))
                //println ">>>res=" << res
                if(res != 'Error') {
                    out.write(res.toString())
                }
            } // exec = search
            else if(exec == 'status') { // GoogleFeed

                def json = mysql.getStatus()
                out.write(json)

            } // exec = status
            else if(exec == 'changePrice') { // GoogleFeed

                def accwareid = request.getParameter("sku")
                def userid = request.getParameter("uid")
                def sellprice = request.getParameter("sprc")
                def reslprice = request.getParameter("rprc")
                //println "accwareid=${accwareid} userid=${userid} sellprice=${sellprice} reslprice=${reslprice}"

                // save price to bookmaker
                bookmakerfeed.savePrice(accwareid, sellprice, reslprice)

                // save price and result to mysql
                mysql.updatePrice(userid, accwareid, sellprice, reslprice)

            } // exec = changePrice
            else if(exec == 'compuveststock') { // cron update every hour

                out.write("<html><head><title>Compuvest Stock update to google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    def count = 1, insert = 0, update = 0, delete = 0, pageSize = 20
                    //def vendors = mysql.getVendorsTablePefokart()
                    //vendors.each { subcatid, vends ->
                    for( page in 0..100000 ) {
                        //if(page == 1) break // test for 1 item

                        //def items = mysql.getCompuvestStock(page, subcatid, vends)
                        def items = mysql.getCompuvestStock(page, pageSize)
                        //println "items=${items}"
                        if(!items.size()) break

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        //println "batch=\n${batch}"

                        // send to google
                        def xmlResult = googlefeed.sendBatch(batch)
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        //println "parseResult=${pres}"

                        // save price and result to mysql
                        mysql.saveResult(items)

                        // show parse result
                        def sres = datafeed.showResult(items, count)
                        insert += sres['insert']
                        update += sres['update']
                        delete += sres['delete']
                        count += pageSize

                        out.write(sres['html'])
                        out.flush()
                        // parse result
                        // write result to mysql
                    }
                    out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                    println "CompuvestStock: insert: ${insert}, update: ${update}, delete: ${delete}"
                    //}
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    println "compuveststock: token error"
                }
                out.write("</table></body>")
            } // exec = compuveststock
            else if(exec == 'allstock') { // cron update every hour

                out.write("<html><head><title>All Stock update to google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    // write to file
                    new File("/tmp/allstock.txt").withWriter { outfile ->
                        outfile.writeLine("sku,price,action,code,status")

                        def count = 1, insert = 0, update = 0, delete = 0, pageSize = 20
                        for( page in 0..100000 ) {
                            //if(page == 2) break // test for 1 item

                            //def items = mysql.getAllStock(page, subcatid, vends)
                            def items = mysql.getAllStock(page, pageSize)
                            //println "items=${items}"
                            if(!items.size()) break

                            // make batch file
                            def batch = datafeed.makeBatch(items)
                            //println "batch=\n${batch}"

                            // send to google
                            def xmlResult = googlefeed.sendBatch(batch)
                            //println "xmlResult=${xmlResult}"

                            // parse result
                            def pres = datafeed.parseResult(xmlResult, items)
                            //println "parseResult=${pres}"

                            // save price and result to mysql
                            mysql.saveResult(items)

                            // write to file
                            items.each { accwareid, item ->
                                outfile.writeLine("${accwareid},${item.field['sellprice']},${item.action['type']},${item.status['code']},${item.status['reason']}")
                            }

                            // show parse result
                            def sres = datafeed.showResult(items, count)
                            insert += sres['insert']
                            update += sres['update']
                            delete += sres['delete']
                            count += pageSize

                            out.write(sres['html'])
                            out.flush()
                            // parse result
                            // write result to mysql
                        }
                        out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                        println "AllStock: insert: ${insert}, update: ${update}, delete: ${delete}"
                    } // new File
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    println "allstock: token error"
                }
                out.write("</table></body>")
            } // allstock
            else if(exec == 'notourstock') { // cron update every hour

                out.write("<html><head><title>Not Our Stock update to google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    // write to file
                    new File("/tmp/notourstock.txt").withWriter { outfile ->
                        outfile.writeLine("sku,price,action,code,status")

                        def count = 1, insert = 0, update = 0, delete = 0, pageSize = 20
                        for( page in 0..100000 ) {
                            //if(page == 2) break // test for 1 item

                            def items = mysql.getNotOurStock(page, pageSize)
                            //println "items=${items}"
                            if(!items.size()) break

                            // make batch file
                            def batch = datafeed.makeBatch(items)
                            //println "batch=\n${batch}"

                            // send to google
                            def xmlResult = googlefeed.sendBatch(batch)
                            //println "xmlResult=${xmlResult}"

                            // parse result
                            def pres = datafeed.parseResult(xmlResult, items)
                            //println "parseResult=${pres}"

                            // save price and result to mysql
                            mysql.saveResult(items)

                            // write to file
                            items.each { accwareid, item ->
                                outfile.writeLine("${accwareid},${item.field['sellprice']},${item.action['type']},${item.status['code']},${item.status['reason']}")
                            }

                            // show parse result
                            def sres = datafeed.showResult(items, count)
                            insert += sres['insert']
                            update += sres['update']
                            delete += sres['delete']
                            count += pageSize

                            out.write(sres['html'])
                            out.flush()
                            // parse result
                            // write result to mysql
                        }
                        out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                        println "Notourstock: insert: ${insert}, update: ${update}, delete: ${delete}"
                    } // new File
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    println "notourstock: token error"
                }
                out.write("</table></body>")
            } // notourstock
            else if(exec == 'removeitems') {

                out.write("<html><head><title>Remove items from google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    // write to file
                    new File("/tmp/remove.txt").withWriter { outfile ->
                        outfile.writeLine("sku,price,action,code,status")

                        def count = 1, pageSize = 20
                        for( page in 0..100000 ) {
                            //if(page == 2) break // test for 1 item

                            //def items = mysql.getAllStock(page, subcatid, vends)
                            def items = mysql.getRemoveStock(page, pageSize)
                            //println "items=${items}"
                            if(!items.size()) break

                            // make batch file
                            def batch = datafeed.makeBatch(items)
                            //println "batch=\n${batch}"

                            // send to google
                            def xmlResult = googlefeed.sendBatch(batch)
                            //println "xmlResult=${xmlResult}"

                            // parse result
                            def pres = datafeed.parseResult(xmlResult, items)
                            //println "parseResult=${pres}"

                            // save price and result to mysql
                            mysql.saveResult(items)

                            // write to file
                            items.each { accwareid, item ->
                                outfile.writeLine("${accwareid},${item.action['type']},${item.status['code']},${item.status['reason']}")
                            }

                            // show parse result
                            def sres = datafeed.showResult(items, count)
                            count =+ pageSize

                            out.write(sres['html'])
                            out.flush()
                            // parse result
                            // write result to mysql
                        }
                        out.write("<tr><td colspan='6'>&nbsp;</td></tr>")
                        println "Remove items:"
                    } // new File
                }
                else {
                    out.write("<tr><td colspan='9'>token error</td></tr>")
                    println "allstock: token error"
                }
                out.write("</table></body>")
            } // removeitems
            else if(exec == 'removeallstock') {

                out.write("<html><head><title>Remove ALL items from google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    // write to file
                    new File("/tmp/removeallstock.txt").withWriter { outfile ->
                        outfile.writeLine("sku,price,action,code,status")

                        def count = 1, pageSize = 20
                        for( page in 0..100000 ) {
                            //if(page == 2) break // test for 1 item

                            //def items = mysql.getAllStock(page, subcatid, vends)
                            def items = mysql.getRemoveAllStock(page, pageSize)
                            //println "items=${items}"
                            if(!items.size()) break

                            // make batch file
                            def batch = datafeed.makeBatch(items)
                            //println "batch=\n${batch}"

                            // send to google
                            def xmlResult = googlefeed.sendBatch(batch)
                            //println "xmlResult=${xmlResult}"

                            // parse result
                            def pres = datafeed.parseResult(xmlResult, items)
                            //println "parseResult=${pres}"

                            // save price and result to mysql
                            mysql.saveResult(items)

                            // write to file
                            items.each { accwareid, item ->
                                outfile.writeLine("${accwareid},${item.action['type']},${item.status['code']},${item.status['reason']}")
                            }

                            // show parse result
                            def sres = datafeed.showResult(items, count)
                            count += pageSize

                            out.write(sres['html'])
                            out.flush()
                            // parse result
                            // write result to mysql
                        }
                        out.write("<tr><td colspan='6'>&nbsp;</td></tr>")
                        println "Remove remove All stock:"
                    } // new File
                }
                else {
                    out.write("<tr><td colspan='9'>token error</td></tr>")
                    println "allstock: token error"
                }
                out.write("</table></body>")
            } // removeallstock
            else if(exec == 'testitem') { // ?exec=testitem&action=[insert|update|delete]&sku=405003687-41

                out.write("<html><head><title>Test Google Item</title></head><body>")
                if(token != 'Error') {
                    def action = request.getParameter("action"), sku = request.getParameter("sku")
                    if(action && sku) {
                        out.write("<li/>action: ${action}")
                        out.write("<li/>accwareCatID: ${sku}")

                        def items = mysql.getItem(action, sku)
                        //println "item=${item}"
                        if(!items.size()) {
                            out.write("<li/><h3 style='color:red;'>not find such item accwareCatID: ${sku}</h3>")
                            return
                        }

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        out.write("<br/><pre>${batch}</pre>")
                        //println "batch=\n${batch}"

                        def xmlResult = googlefeed.sendBatch(batch)
                        out.write("<br/><pre>${xmlResult}</pre>")
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        out.write("<br/><pre>${pres}</pre>")
                        //println "parseResult:\n${pres}\nitem:\n${item}"

                        // save result to mysql
                        mysql.saveResult(items)
                    }
                    else {
                        out.write("<li/>miss action or sku<br/>use: ?exec=testitem&action=[insert|update|delete|query]&sku=")
                    }
                }
                else {
                    out.write("<li/>token error")
                }
            }
            else if(exec == 'updateexpared') { // cron update every hour

                out.write("<html><head><title>Expared Stock update to google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    def items, count = 1, insert = 0, update = 0,  delete = 0, pagesize = 20
                    //def vendors = mysql.getVendorsTablePefokart()
                    //vendors.each { subcatid, vends ->
                    for( page in 0..100000 ) {

                        //items = mysql.getExparedStock(page, pagesize, subcatid, vends)
                        items = mysql.getExparedStock(page, pagesize)
                        //println "items=${items}"
                        if(!items.size()) break

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        //println "batch=\n${batch}"

                        // send to google
                        def xmlResult = googlefeed.sendBatch(batch)
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        //println "parseResult=${pres}"

                        // save result to mysql
                        mysql.saveResult(items)

                        // show parse result
                        def sres = datafeed.showResult(items, count)
                        insert += sres['insert']
                        update += sres['update']
                        delete += sres['delete']
                        count += pagesize

                        out.write(sres['html'])
                        out.flush()
                        // parse result
                        // write result to mysql
                    }
                    out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                    println "ExparedStock: insert: ${insert}, update: ${update}, delete: ${delete}"
                    //}
                }
            }
            else if(exec == 'updateallstock') { // manual

                out.write("<html><head><title>Update ALL Stock to google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                if(token != 'Error') {
                    out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")

                    def items, count = 1, insert = 0, update = 0,  delete = 0, pagesize = 20
                    //def vendors = mysql.getVendorsTablePefokart()
                    //vendors.each { subcatid, vends ->
                    for( page in 0..100000 ) {

                        items = mysql.getUpdateAllStock(page)
                        //println "items=${items}"
                        if(!items.size()) break

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        //println "batch=\n${batch}"

                        // send to google
                        def xmlResult = googlefeed.sendBatch(batch)
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        //println "parseResult=${pres}"

                        // save result to mysql
                        mysql.saveResult(items)

                        // show parse result
                        def sres = datafeed.showResult(items, count)
                        insert += sres['insert']
                        update += sres['update']
                        delete += sres['delete']
                        count += pagesize

                        out.write(sres['html'])
                        out.flush()
                        // parse result
                        // write result to mysql
                    }
                    out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                    println "ExparedStock: insert: ${insert}, update: ${update}, delete: ${delete}"
                    //}
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    println "expared: token error"
                }
                out.write("</table></body></html>")
            } // exec = allstock
            else if(exec == 'weekly') {

                def outlog = new StringBuilder()

                outlog << "\n-------------START WEAKLY-------------\n"
                out.write("<html><head><title>Weekly Discount price to google</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")
                if(token != 'Error') {

                    def count = 1, insert = 0, update = 0,  delete = 0, error = 0, pageSize = 20
                    //def vendors = mysql.getVendorsTablePefokart()
                    //vendors.each { subcatid, vends ->
                    for( page in 0..100000 ) {
                        //if(page == 1) break // test for 1 item

                        // read page items from mysql
                        //def items = mysql.getWeeklyItems(page, subcatid, vends)
                        def items = mysql.getWeeklyItems(page, pageSize)
                        //println "items=${items}"
                        if(!items.size()) break

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        //println "batch=\n${batch}"

                        // send to google
                        def xmlResult = googlefeed.sendBatch(batch)
                        //def xmlResult = googlefeed.sendBatchReturn()
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        //println "parseResult=${pres}"

                        // save price to bookmaker
                        bookmakerfeed.updatePrice(items)

                        // save price and result to mysql
                        mysql.savePrice(items)

                        // show parse result
                        def result = datafeed.showResult(items, count)

                        insert += result['insert']
                        update += result['update']
                        delete += result['delete']
                        count += pageSize

                        out.write(result['html'])
                        out.flush()
                    } // for

                    out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                    outlog <<  "weekly: insert: ${insert}, update: ${update}, delete: ${delete}\n"
                    //}
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    outlog << "weekly: token error"
                }
                out.write("</table></body></html>")
                outlog <<  "-------------STOP WEAKLY-------------\n"
                println outlog
            } // exec = weekly
            else if(exec == 'holiday') {

                def outlog = new StringBuilder()

                outlog << "\n-------------START HOLIDAY DISCOUNT-------------\n"
                out.write("<html><head><title>Holiday Discount price to google</title></head><body>")

                def percent = request.getParameter("percent") as Integer
                if(percent == 0) {
                    out.write("<h3 style='color:red;'>Percent = 0</h3>")
                    out.write("</body></html>")
                    return
                }


                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")
                if(token != 'Error') {

                    def count = 1, insert = 0, update = 0,  delete = 0, error = 0, pageSize = 20
                    //def vendors = mysql.getVendorsTablePefokart()
                    //vendors.each { subcatid, vends ->
                    for( page in 0..100000 ) {
                        //if(page == 1) break // test for 1 item

                        // read page items from mysql
                        //def items = mysql.getHolidayItems(page, percent, subcatid, vends)
                        def items = mysql.getHolidayItems(page, percent, pageSize)
                        //println "items=${items}"
                        if(!items.size()) break

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        //println "batch=\n${batch}"

                        // send to google
                        def xmlResult = googlefeed.sendBatch(batch)
                        //def xmlResult = googlefeed.sendBatchReturn()
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        //println "parseResult=${pres}"

                        // save price to bookmaker
                        bookmakerfeed.updatePrice(items)

                        // save price and result to mysql
                        mysql.saveHolidayPrice(items)

                        // show parse result
                        def result = datafeed.showResult(items, count)

                        insert += result['insert']
                        update += result['update']
                        delete += result['delete']
                        count += pageSize

                        out.write(result['html'])
                        out.flush()
                    } // for

                    out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                    outlog <<  "holiday: insert: ${insert}, update: ${update}, delete: ${delete}\n"
                    //}
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    outlog << "holiday: token error"
                }
                out.write("</table></body></html>")
                outlog <<  "-------------STOP HOLIDAY DISCOUNT-------------\n"
                println outlog
            } // exec = holiday
            else if(exec == 'backup') {

                def outlog = new StringBuilder()

                outlog << "\n-------------BACKUP HOLIDAY-------------\n"
                out.write("<html><head><title>Backup holiday price</title></head><body>")
                out.write("<table border=1 style='text-align:center;font-size:11px;border-collapse:collapse;'>")
                out.write("<tr><th>#</th><th>accware sku</th><th>Reseller Price(old:new)</th><th>Sell Price(old:new)</th><th>action</th><th>code</th><th>status</th><th>accware status</th></tr>")
                if(token != 'Error') {

                    def count = 1, insert = 0, update = 0,  delete = 0, error = 0, pageSize = 20
                    for( page in 0..100000 ) {
                        //if(page == 1) break // test for 1 item

                        // read page items from mysql
                        def items = mysql.getHolidayBackupItems(page, pageSize)
                        //println "items=${items}"
                        if(!items.size()) break

                        // make batch file
                        def batch = datafeed.makeBatch(items)
                        //println "batch=\n${batch}"

                        // send to google
                        def xmlResult = googlefeed.sendBatch(batch)
                        //def xmlResult = googlefeed.sendBatchReturn()
                        //println "xmlResult=${xmlResult}"

                        // parse result
                        def pres = datafeed.parseResult(xmlResult, items)
                        //println "parseResult=${pres}"

                        // save price to bookmaker
                        bookmakerfeed.updatePrice(items)

                        // save price and result to mysql
                        mysql.saveBackupPrice(items)

                        // show parse result
                        def result = datafeed.showResult(items, count)

                        insert += result['insert']
                        update += result['update']
                        delete += result['delete']
                        count += pageSize

                        out.write(result['html'])
                        out.flush()
                    } // for

                    out.write("<tr><td colspan='8'>insert: ${insert}, update: ${update}, delete: ${delete}</td></tr>")
                    outlog <<  "backup: insert: ${insert}, update: ${update}, delete: ${delete}\n"
                }
                else {
                    out.write("<tr><td colspan='11'>token error</td></tr>")
                    outlog << "holiday backup: token error"
                }
                out.write("</table></body></html>")
                outlog <<  "-------------STOP HOLIDAY BACKUP-------------\n"
                println outlog
            } // exec = backup
            else if(exec == 'sendftp') { // GoogleFeed

                out.write("<html><head><title>Make FTP file to google</title></head><body>")

                def start = System.currentTimeMillis()
                mysql.initTempTable()
                out.write("<li/>init temp table: ${System.currentTimeMillis() - start}ms.")
                out.flush()

                def makeVendor = request.getParameter("make"), message, count = 0, vendors, body = new StringBuilder()
                if(makeVendor) {

                    if(makeVendor == 'MLB') {

                        start = System.currentTimeMillis()
                        vendors = mysql.getVendorsFromPefokart("IN (9)")
                        message = "get ${makeVendor} vendors[${vendors.size()}]: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        count = mysql.makeFile(vendors, 20, "compuvestMLB.txt", mysql.COMPUVESTCOM); // > $20.00
                        message = "make file ${makeVendor}: ${count} items ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        //def ftp = new FtpService()
                        //ftp.send("compuvestMLB.txt", "compuvestMLB.txt")
                        message = "send to ftp: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                    }
                    else if(makeVendor == 'SNX') {

                        start = System.currentTimeMillis()
                        vendors = mysql.getVendorsFromPefokart("IN (69)")
                        message = "get ${makeVendor} vendors[${vendors.size()}]: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        count = mysql.makeFile(vendors, 5, "compuvestSNX.txt", mysql.COMPUVESTCOM); // > $5.00
                        message = "make file ${makeVendor}: ${count} items ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        def ftp = new FtpService()
                        ftp.send("compuvestSNX.txt", "compuvestSNX.txt")
                        message = "send to ftp: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()
                    }
                    else if(makeVendor == 'CVS') {

                        start = System.currentTimeMillis()
                        vendors = mysql.getVendorsFromPefokart("IN (2,83,27,29)") //CVS=2, CAS=83, ADV=27, AAA=29
                        message = "get ${makeVendor} vendors[${vendors.size()}]: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        count = mysql.makeFile(vendors, 5, "compuvestCVS.txt", mysql.COMPUVESTCOM); // > $5.00
                        message = "make file ${makeVendor}: ${count} items ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        def ftp = new FtpService()
                        ftp.send("compuvestCVS.txt", "compuvestCVS.txt")
                        message = "send to ftp: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()
                    }
                    else if(makeVendor == 'ALL') {

                        start = System.currentTimeMillis()
                        vendors = mysql.getVendorsFromPefokart("NOT IN (2,83,27,29,9,69)") // CVS=2, CAS=83, ADV=27, AAA=29, MLB=9, SNX=69
                        message = "get ${makeVendor} vendors[${vendors.size()}]: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        count = mysql.makeFile(vendors, 5, "compuvest1.txt", mysql.COMPUVESTCOM); // > $5.00
                        message = "make file ${makeVendor}: ${count} items ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()

                        start = System.currentTimeMillis()
                        def ftp = new FtpService()
                        ftp.send("compuvest1.txt", "compuvest1.txt")
                        message = "send to ftp: ${System.currentTimeMillis() - start}ms.\n"
                        body << message
                        out.write("<li/>${message}")
                        out.flush()
                    }

                    mail.send(
                            "webinfo@compuvest.com",
                        ["vasil@compuvest.com"],
                            "Update froogle ${makeVendor} ${count} items write to file ${new Date()}",
                        body.toString(),
                            "text/plain"
                    )

                    out.write("<li/>send email")
                    out.flush()
                } // makeVendor

                out.write("</body>")
            } // exec = sendftp
        }
        finally {
            out.close()
        }
    }

/*
[?&]dry-run

http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/

*/

    def image = """
        <img src='http://chart.apis.google.com/chart?cht=p3&chs=500x150&chd=s:JDJJJ&chl=Olga|Vasya|Serega|Sandro|Boroda' alt='it department'/>
    """

    def void doGet(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    def void doPost(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    String getServletInfo() {
        return "GoogleService"
    }
    def void destroy() {
        mysql           = null
        googlefeed      = null
        bookmakerfeed   = null
        datafeed        = null
    }
}

